/*
* Copyright (c) 2021,
* All rights reserved.
*
* 文件名称：main.c
* 创建日期：2021/12/19
* 摘 要：基础服务主函数
*
* 当前版本：1.0
* 作 者：赵满刚
* 完成日期：
*/


#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <time.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>

#include "../public/write_log.h"
#include "base_server.h"
#include "db_oper.h"




int main(int argc, char* argv[])
{
    char address[ADDRESS_MAX_LENGTH] = "0.0.0.0";
    int port = 8888;
    pid_t pid;
    int listenfd = -1; //监听套接字
    int connfd = -1; //连接套接字
    socklen_t clilen;
    struct sockaddr_in servaddr,cliaddr;
    
    user_opt_deal(argc, argv, address, sizeof(address), &port);
    write_log(LOG_INFO, "listen \n address: %s\n port: %d", address, port);

    listenfd = socket(AF_INET,SOCK_STREAM,0);
    if (-1 == listenfd)
    {
        //socket error
        write_log(LOG_ERROR,"socket error\n");
        return 0;
    }

    bzero(&servaddr,sizeof(servaddr));

    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(port);
    if (-1 == bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr)))
    {
        write_log(LOG_ERROR,"bind error\n");
        return 0;
    }

    if (-1 == listen(listenfd,LISTENQ))
    {
        write_log(LOG_ERROR,"listen error\n");
        return 0;
    }

    for ( ; ;)
    {
        clilen = sizeof(cliaddr);
        if (-1 == (connfd = accept(listenfd,(struct sockaddr *) &cliaddr, &clilen)))
        {
            write_log(LOG_ERROR,"accept error\n");
            return 0;
        }
        write_log(LOG_DEBUG,"connfd %d",connfd);
        
        if ( (pid = fork()) == 0)
        {
            /* 子进程 */
            close(listenfd);

            /* 客户端请求处理 */
            client_request_deal(connfd);

            close(connfd);
            exit(0);
        }

        close(connfd);
    }
    return 0;
}